<script setup>

import {ref, onMounted, watch, computed} from 'vue';
import axios from "axios";
import {snackbar} from './store'
import moment from 'moment'

// 查询
const itemsPerPage = ref(10);
const pageNo = ref(1)
const headers = [
    {title: '序号', key: 'num', sortable: false},
    // {title: '巡检点位', key: 'buildingId', sortable: false},
    // {title: '巡检楼层', key: 'floorId', sortable: false},
    {title: '巡检地点', key: 'placeName', sortable: false},
    {title: '巡检员', key: 'userName', sortable: false},
    {title: '巡检时间', key: 'recordTime', sortable: false},
    {title: '是否异常', key: 'fireType', sortable: false},
    {title: '详情描述', key: 'checkContent', sortable: false},
    {title: '事件状态', key: 'eventType', sortable: false},
    {title: '处理方法', key: 'handleMethod', sortable: false},
    {title: '处理结果', key: 'handleResult', sortable: false},
    {title: '操作', key: 'actions', sortable: false}
];
const items = ref([]);
const loading = ref(true);
const totalItems = ref(0);

const search = ref('');
const name = ref(null);
const fireType = ref(0);
const startDate = ref(null);
const endDate = ref(null);
const dateSearchStart = ref(new Date());
const dateSearchEnd = ref(new Date());
const userList = ref([]);
const buildingList = ref([]);
const floorList = ref([]);
const checkPlaceList = ref([]);
const editType = ref(false);
const isShowDialogStart = ref(false);
const isShowDialogEnd = ref(false);
const itemsId = ref([]);
watch(name, () => {
    search.value = name.value
})
watch(fireType, () => {
    search.value = fireType.value
})
watch(startDate, () => {
    search.value = startDate.value
})
watch(endDate, () => {
    search.value = endDate.value
})

function loadItems({page, itemsPerPage}) {
    loading.value = true;
    pageNo.value = page
    axios.post('/checkFireRecord/select', {
        pageNo: page,
        pageSize: itemsPerPage,
        placeName: name.value,
        fireType: fireType.value,
        startDate: startDate.value,
        endDate: endDate.value
    }).then(({data}) => {
        items.value = data.data.records;
        totalItems.value = data.data.total;
        loading.value = false;
    })
}

onMounted(() => {
    loadItems({page: 1, itemsPerPage: itemsPerPage.value});
    axios.post('/user/selectPage', {
        pageNo: 1,
        pageSize: 10000,
        delFlag: '0'
    }).then(({data}) => {
        userList.value = data.data.records;
    })
    axios.post('/checkPlace/getAll', {}).then(({data}) => {
        checkPlaceList.value = data.data;
    })
    axios.post('/checkFireBuilding/getAll', {}).then(({data}) => {
        buildingList.value = data.data;
    })
    axios.post('/checkFireFloor/getAll', {}).then(({data}) => {
        floorList.value = data.data;
    })
});

// 增改
const isShowDialog = ref(false)
const dialogEnum = {
    update: '编辑',
    create: '新增',
    check: "查看"
}
const dialogType = ref(null)
const isShowDeleteDialog = ref(false)
const editedItem = ref({
    userId: "",
    recordTime: "",
    placeId: "",
    checkContent: "",
    buildingId: "",
    floorId: "",
    handleMethod: "",
    handleResult: "",
    eventType: "",
    fireType: ""
});

function resetEditedItem() {
    editedItem.value = {
        userId: "",
        recordTime: "",
        placeId: "",
        checkContent: "",
        buildingId: "",
        floorId: "",
        handleMethod: "",
        handleResult: "",
        eventType: "",
        fireType: ""
    }
}

function clickNew() {
    dialogType.value = dialogEnum.create
    resetEditedItem()
    isShowDialog.value = true
}

function close() {
    isShowDialog.value = false
    resetEditedItem()
    dialogType.value = null
}

function clickEdit(item, type) {
    editType.value = type
    editedItem.value = Object.assign({}, item)
    editedItem.value.eventType += ""
    editedItem.value.fireType += ""
    itemsId.value = JSON.parse(editedItem.value.itemsId)
    isShowDialog.value = true
    if(type) {
        dialogType.value = dialogEnum.update        
    } else {
        dialogType.value = dialogEnum.check
    }
}

function save() {
    if (dialogType.value === dialogEnum.update) {
        axios({
            method: 'POST',
            url: '/checkFireRecord/update',
            data: editedItem.value
        }).then(() => {
            snackbar.info('编辑成功')
            close()
            loadItems({page: pageNo.value, itemsPerPage: itemsPerPage.value})
        })
    } else if (dialogType.value === dialogEnum.create) {
        axios({
            method: 'POST',
            url: '/checkFireRecord/save',
            data: editedItem.value
        }).then((res) => {
            console.log(res.data)
            snackbar.info('创建成功')
            close()
            loadItems({page: pageNo.value, itemsPerPage: itemsPerPage.value})
        })
    }
}

// 删
const beDeleteItem = ref({})

function clickDelete(item) {
    isShowDeleteDialog.value = true
    beDeleteItem.value = item
}

function clickDeleteConfirm() {
    axios.get('/sys_role/role/delRole/?roleId=' + beDeleteItem.value.id).then(() => {
        snackbar.info("删除成功")
        loadItems({page: 1, itemsPerPage: itemsPerPage.value})
        clickCloseDelete()
    })
}

function clickCloseDelete() {
    isShowDeleteDialog.value = false
    beDeleteItem.value = null
}

function changeDate() {
    startDate.value = moment(dateSearchStart.value).format('YYYY-MM-DD 00:00:00')
    isShowDialogStart.value = false
}

function changeDateEnd() {
    endDate.value = moment(dateSearchEnd.value).format('YYYY-MM-DD 23:59:59')
    isShowDialogEnd.value = false
}

function downloadFile() {
    let obj = {
        placeName: name.value,
        fireType: fireType.value,
        startDate: startDate.value,
        endDate: endDate.value
    }
    axios({
        method: "POST",
        url: "/checkFireRecord/export",
        responseType: 'blob',
        data: obj
    }).then(res => {
        console.log(res)
    }, err => {
        let blob = new Blob([err.data], {type: "application/vnd.ms-excel"});
        let fileName = `${new Date().getTime()}消防巡检记录.xls`
        if ("download" in document.createElement("a")) {
            // 支持a标签download的浏览器
            const link = document.createElement("a"); // 创建a标签
            link.download = fileName; // a标签添加属性
            link.style.display = "none";
            link.href = URL.createObjectURL(blob);
            document.body.appendChild(link);
            link.click(); // 执行下载
            URL.revokeObjectURL(link.href); // 释放url
            document.body.removeChild(link); // 释放标签
        } else {
            // 其他浏览器
            navigator.msSaveBlob(blob, fileName);
        }
    })
}

</script>

<template>
    <v-toolbar density="compact">
        <v-toolbar-title>消防巡查记录管理</v-toolbar-title>
        <v-text-field v-model="startDate" readonly :clearable="true" hide-details placeholder="开始时间" @click="isShowDialogStart = true"></v-text-field>
        <v-dialog v-model="isShowDialogStart" max-width="500px">
            <v-date-picker v-model="dateSearchStart" @update:model-value="changeDate"></v-date-picker>
        </v-dialog>
        <v-text-field v-model="endDate" readonly :clearable="true" hide-details placeholder="结束时间" @click="isShowDialogEnd = true"></v-text-field>
        <v-dialog v-model="isShowDialogEnd" max-width="500px">
            <v-date-picker v-model="dateSearchEnd" @update:model-value="changeDateEnd"></v-date-picker>
        </v-dialog>
        <v-select v-model="fireType" :items="[{value:0,title:'正常'},{value:1,title:'异常'}]" label="是否异常" :clearable="true" hide-details></v-select>
        <v-text-field v-model="name" :clearable="true" hide-details placeholder="查询名称"></v-text-field>
        <v-btn icon="mdi-upload" @click="downloadFile"></v-btn>
        <v-dialog v-model="isShowDialog" max-width="500px">
            <template v-slot:activator="{ props }">
                <v-btn icon="mdi-plus" v-on:click="clickNew" v-bind="props"></v-btn>
            </template>
            <v-card>
                <v-card-title>{{ dialogType }}</v-card-title>
                <v-card-text>
                    <v-text-field :readonly="!editType" v-model="editedItem.checkContent" label="详情描述" required></v-text-field>
                    <v-select
                    v-model="editedItem.buildingId"
                    :items="buildingList"
                    @update:model-value="changeFloor"
                    item-title="buildingName"
                    item-value="id"
                    label="建筑名称"
                    placeholder="建筑名称"
                    :readonly="!editType"></v-select>
                    <v-select
                    v-model="editedItem.floorId"
                    :items="floorList"
                    item-title="floorName"
                    item-value="id"
                    label="楼层名称"
                    placeholder="楼层名称"
                    :readonly="!editType"></v-select>
                    <v-select :readonly="!editType" v-model="editedItem.userId" label="巡检员" required :items="userList" item-value="id" item-title="nickname"></v-select>
                    <v-text-field :readonly="!editType" v-model="editedItem.recordTime" label="记录时间"></v-text-field>
                    <v-text-field :readonly="!editType" v-model="editedItem.handleMethod" label="处理方法" required></v-text-field>
                    <v-text-field :readonly="!editType" v-model="editedItem.handleResult" label="处理结果" required></v-text-field>
                    <v-select :readonly="!editType" v-model="editedItem.eventType" :items="[{value:'0',title:'待处理'},{value:'1',title:'处理中'},{value:'1',title:'已办结'},{value:'1',title:'超时未办'},{value:'1',title:'驳回'}]"
                    label="事件状态"></v-select>
                    <v-select :readonly="!editType" v-model="editedItem.fireType" :items="[{value:'0',title:'正常'},{value:'1',title:'异常'}]"
                    label="是否异常"></v-select>
                    <h2>消防巡检项：</h2>
                    <div v-for="(item, index) in itemsId" :key="item.id">
                        <span>{{ index + 1 }}. {{ item.itemName }}</span>
                        :
                        <el-button type="primary" plain size="mini">{{ item.itemIf ? '正常' : '异常' }}</el-button> 
                        <br>       
                    </div>
                </v-card-text>
                <v-card-actions>
                    <v-btn color="primary" variant="text" @click="close">关闭</v-btn>
                    <v-btn v-if="!editType" color="primary" variant="text" @click="save">确定</v-btn>
                    <v-btn v-else color="primary" variant="text" @click="save">修改</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
        <v-dialog v-model="isShowDeleteDialog" max-width="500px">
            <v-card>
                <v-card-title class="text-h5">确定删除?</v-card-title>
                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn color="blue-darken-1" variant="text" @click="clickCloseDelete">取消</v-btn>
                    <v-btn color="blue-darken-1" variant="text" @click="clickDeleteConfirm">确定</v-btn>
                    <v-spacer></v-spacer>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </v-toolbar>
  <!--  分页文本待更换   items-per-page-text="每页数量"-->
    <v-data-table-server :search="search" :items-per-page="itemsPerPage" :headers="headers" :items-length="totalItems"
    :items="items"
    :loading="loading"
    class="elevation-1"
    items-per-page-text="每页数量"
    @update:options="loadItems">
        <template v-slot:item.num="{ index }">
            <span>{{ index + 1 }}</span>
        </template>
        <template v-slot:item.fireType="{ item }">
            <span v-if="item.raw.fireType == 0">正常</span>
            <span v-if="item.raw.fireType == 1">异常</span>
        </template>
        <template v-slot:item.eventType="{ item }">
            <span v-if="item.raw.eventType == 0 && item.fireType == 1">待处理</span>
            <span v-if="item.raw.eventType == 1 && item.fireType == 1">处理中</span>
            <span v-if="item.raw.eventType == 2 && item.fireType == 1">已办结</span>
            <span v-if="item.raw.fireType == 0">正常事件</span>
        </template>
        <template v-slot:item.buildingId="{ item }">
            <!-- <span v-for="k in buildingList" v-show="k.id == item.buildingId">{{ k.buildingName }}</span>
            - -->
            <span v-if="item.raw.deviceType == 0">消火栓</span>
            <span v-if="item.raw.deviceType == 1">灭火器1</span>
            <span v-if="item.raw.deviceType == 2">灭火器2</span>
            <span v-if="item.raw.deviceType == 3">灭火器3</span>
        </template>
        <template v-slot:item.userName="{ item }">
            <!-- <span v-for="k in userList" v-show="k.id == item.raw.userId">{{ k.nickname }}</span> -->
            <span>{{ JSON.parse(item.raw.handleFlow)[0].name }}</span>
        </template>
        <template v-slot:item.checkContent="{ item }">
            <span>{{ item.raw.checkContent ? item.raw.checkContent : '无' }}</span>
        </template>
        <template v-slot:item.handleMethod="{ item }">
            <span>{{ item.raw.handleMethod ? item.raw.handleMethod : '无' }}</span>
        </template>
        <template v-slot:item.handleResult="{ item }">
            <span>{{ item.raw.handleResult ? item.raw.handleResult : '无' }}</span>
        </template>
        <template v-slot:item.floorId="{ item }">
            <span v-for="k in floorList" v-show="k.id == item.raw.floorId">{{ k.floorName }}</span>
        </template>
        <template v-slot:item.actions="{ item }">
            <v-btn icon="mdi-file-find" variant="text" @click="clickEdit(item.raw, false)"></v-btn>
            <v-btn icon="mdi-book-edit" variant="text" @click="clickEdit(item.raw, true)"></v-btn>
            <!-- <v-btn icon="mdi-delete" variant="text" @click="clickDelete(item)"></v-btn> -->
        </template>
    </v-data-table-server>
</template>

<style scoped lang="less">

</style>
